/*
*    l3qd - Light, light, lightweight queue
*    Copyright (C) 2024  Marcus Pedersén marcus@marcux.org
*
*    This program is free software: you can redistribute it and/or modify
*    it under the terms of the GNU General Public License as published by
*    the Free Software Foundation, either version 3 of the License, or
*    (at your option) any later version.
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU General Public License for more details.
*
*    You should have received a copy of the GNU General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package list

import (
	"encoding/json"
	"fmt"
	"github.com/spf13/cobra"
	"notabug.org/marcux/l3q/internal/client"
	"notabug.org/marcux/l3q/internal/common"
	"os"
	"strings"
)

var listQueueCmdFlagLong, listQueueCmdFlagVerbose bool

var listQueueCmd = &cobra.Command{
	Use:   "queue",
	Short: "Lists all running and queued jobs in l3q",
	Long: `Description:
  Lists all running and queued jobs in l3q.
  The values in Task column are the number of tasks: 
  Running/Terminated/Error:Total`,
	Run: func(cmd *cobra.Command, args []string) {
		PrintQueue(listQueueCmdFlagLong, listQueueCmdFlagVerbose, false, 0)
	},
}

// Prints a formated table
// of queued jobs.
func PrintQueue(long bool, verbose bool, history bool, number uint) {
	jobs := []common.Job{}
	var urlSuffix string

	if history {
		if number > 0 {
			urlSuffix = fmt.Sprintf("/job?history&limit=%d", number)
		} else {
			urlSuffix = "/job?history"
		}
	} else {
		urlSuffix = "/job?queue"
	}

	jsonBytes := client.UrlGet(urlSuffix, verbose)
	err := json.Unmarshal(jsonBytes, &jobs)
	if err != nil {
		if verbose {
			fmt.Fprintf(os.Stderr, "Failed to decode json string to struct\n%s\n.", err)
		} else {
			fmt.Fprintf(os.Stderr, "Failed to decode json string.\n")
		}
		os.Exit(1)
	}

	if long {
		headline := strings.Repeat("=", 177)
		line := strings.Repeat("-", 177)

		fmt.Printf("%s\n", headline)
		fmt.Printf("| %s | %-20s | %-20s |         %4s        |        %5s        | %11s | %11s |  %s  |   %s   |   %6s   | %-5s\n",
			"Jobid", "User", "Name", "Init", "Start", "Cores alloc", "Nodes alloc",
			"Tasks R/T/E:N", "State", "Depend", "Nodes")
		fmt.Printf("%s\n", headline)

		for _, j := range jobs {
			u := j.User
			n := j.Name
			t := fmt.Sprintf("%d/%d/%d:%d", j.NoTasksRunning,
				j.NoTasksFinished, j.NoTasksErr,
				j.NoTasksTotal)

			if len(j.User) > 20 {
				u = j.User[:21]
			}

			if len(j.Name) > 20 {
				n = j.Name[:21]
			}

			fmt.Printf("| %5d | %-20s | %-20s | %19s | %19s | %11d | %11d | %15s | %9s | %10s | %s\n",
				j.Id, u, n, j.InitDate, j.StartDate, j.CoresAlloc,
				j.HostsAlloc, t, j.State, j.Depend, j.Nodes)

			fmt.Printf("%s\n", line)
		}
	} else {
		headline := strings.Repeat("=", 121)
		line := strings.Repeat("-", 121)

		fmt.Printf("%s\n", headline)
		fmt.Printf("| %s | %-20s | %-20s | %11s | %11s |  %s  |   %s   | %-5s |\n",
			"Jobid", "User", "Name", "Cores alloc", "Nodes alloc",
			"Tasks R/T/E:N", "State", "Nodes")
		fmt.Printf("%s\n", headline)

		for _, j := range jobs {
			u := j.User
			n := j.Name
			t := fmt.Sprintf("%d/%d/%d:%d", j.NoTasksRunning,
				j.NoTasksFinished, j.NoTasksErr,
				j.NoTasksTotal)

			if len(j.User) > 20 {
				u = j.User[:21]
			}

			if len(j.Name) > 20 {
				n = j.Name[:21]
			}

			nStr := strings.Trim(j.Nodes, " ")
			var non int

			if len(nStr) == 0 {
				non = 0
			} else {
				non = len(strings.Split(nStr, ","))
			}

			fmt.Printf("| %5d | %-20s | %-20s | %11d | %11d | %15s | %9s | %5d |\n",
				j.Id, u, n, j.CoresAlloc, j.HostsAlloc,
				t, j.State, non)
			fmt.Printf("%s\n", line)
		}
	}
}

func init() {
	listQueueCmd.Flags().BoolVarP(&listQueueCmdFlagLong, "long", "l", false, "Print extended, long list.")
	listQueueCmd.Flags().BoolVarP(&listQueueCmdFlagVerbose, "verbose", "v", false, "Print verbose output")
}
